package com.example.turncardapp.model

import java.util.Collections

class CardMatchingGame(count: Int)  {
    var score = 0
        private set

    private val cards: MutableList<Card>

    init {
        // Ensure even number of cards so they can be paired
        val effectiveCount = if (count % 2 == 0) count else count - 1
        val deck = Deck()
        cards = mutableListOf()
        val pairs = effectiveCount / 2
        for (i in 0 until pairs) {
            // draw a random card definition from the deck
            val cardDef = deck.drawRandomCard()
            if (cardDef != null) {
                // create two matching Card instances (same suit and rank) to form a pair
                val c1 = Card(suit = cardDef.suit, rank = cardDef.rank)
                val c2 = Card(suit = cardDef.suit, rank = cardDef.rank)
                cards.add(c1)
                cards.add(c2)
            } else {
                // Deck exhausted unexpectedly; break
                break
            }
        }
        // If requested count was odd, we've created effectiveCount cards; if less due to deck exhaustion, that's fine.
        // Shuffle the cards so pairs are distributed randomly
        Collections.shuffle(cards)
    }

    fun cardAtIndex(index: Int): Card {
        return cards.get(index)
    }

    val MISMATCH_PENALTY = 2
    val MATCH_BONUS = 4
    val COST_TO_CHOOSE = 1

    fun chooseCardAtIndex(index: Int) {
        val card= cardAtIndex(index)
        if (!card.isMatched) {
            if (card.isChosen) {
                card.isChosen = false
            } else {
                for (otherCard in cards) {
                    if (otherCard.isChosen && !otherCard.isMatched) {
                        val matchScore = card.match(arrayOf(otherCard))
                        if (matchScore > 0) {
                            score += matchScore * MATCH_BONUS
                            otherCard.isMatched = true
                            card.isMatched = true
                        } else {
                            score -= MISMATCH_PENALTY
                            otherCard.isChosen = false
                        }
                        break
                    }
                }
                score -= COST_TO_CHOOSE
                card.isChosen = true
            }
        }
    }
}